package com.zenithmind.disk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zenithmind.disk.mapper.FilesMapper;
import com.zenithmind.disk.pojo.domain.Files;
import com.zenithmind.disk.service.FileDownloadService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件下载服务实现
 * 遵循单一职责原则：专注于文件下载功能
 * 遵循依赖倒置原则：依赖抽象接口
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FileDownloadServiceImpl implements FileDownloadService {

    private final FilesMapper filesMapper;

    @Value("${file.upload.path}")
    private String uploadPath;

    @Override
    public void downloadFile(String fileId, String userId, HttpServletResponse response) throws IOException {
        // 获取文件路径
        String filePath = getFilePath(fileId, userId);
        if (filePath == null) {
            throw new RuntimeException("文件不存在或无法下载");
        }

        // 获取文件信息
        Files fileInfo = filesMapper.selectById(fileId);
        if (fileInfo == null) {
            throw new RuntimeException("文件不存在");
        }

        // 获取文件
        File downloadFile = new File(filePath);
        if (!downloadFile.exists()) {
            throw new RuntimeException("文件不存在");
        }

        // 设置响应头
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", 
            "attachment;filename=" + URLEncoder.encode(fileInfo.getFileName(), "UTF-8"));
        response.setContentLength((int) downloadFile.length());

        // 输出文件流
        try (FileInputStream fis = new FileInputStream(downloadFile);
             OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
        }
    }

    @Override
    public void downloadDirectory(String folderId, HttpServletResponse response) throws IOException {
        // 获取文件夹信息
        Files folderInfo = filesMapper.selectById(folderId);
        if (folderInfo == null || folderInfo.getIsDirectory() != 1) {
            throw new RuntimeException("文件夹不存在");
        }

        // 设置响应头
        String zipFileName = folderInfo.getFileName() + ".zip";
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", 
            "attachment;filename=" + URLEncoder.encode(zipFileName, "UTF-8"));

        // 创建ZIP输出流
        try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
            // 递归添加文件夹内容到ZIP
            addFolderToZip(folderInfo.getId(), folderInfo.getFileName(), folderInfo.getUserId(), zipOut);
        }
    }

    @Override
    public String getFilePath(String fileId, String userId) {
        Files file = filesMapper.selectById(fileId);
        if (file == null || file.getStatus() != 1) {
            throw new RuntimeException("文件不存在");
        }
        if (!file.getUserId().equals(userId)) {
            throw new RuntimeException("无权限访问该文件");
        }
        return uploadPath + file.getFilePath();
    }

    /**
     * 递归添加文件夹内容到ZIP
     */
    private void addFolderToZip(String folderId, String folderPath, String userId, ZipOutputStream zipOut) 
            throws IOException {
        // 获取文件夹下的所有文件和子文件夹
        LambdaQueryWrapper<Files> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Files::getParentId, folderId)
                .eq(Files::getStatus, 1)
                .eq(Files::getUserId, userId);
        List<Files> filesList = filesMapper.selectList(queryWrapper);

        for (Files file : filesList) {
            String entryPath = folderPath + "/" + file.getFileName();
            
            if (file.getIsDirectory() == 1) {
                // 如果是文件夹，递归处理
                ZipEntry folderEntry = new ZipEntry(entryPath + "/");
                zipOut.putNextEntry(folderEntry);
                zipOut.closeEntry();
                
                // 递归添加子文件夹内容
                addFolderToZip(file.getId(), entryPath, userId, zipOut);
            } else {
                // 如果是文件，直接添加到ZIP
                String filePath = getFilePath(file.getId(), userId);
                if (filePath != null) {
                    File fileToZip = new File(filePath);
                    if (fileToZip.exists()) {
                        ZipEntry zipEntry = new ZipEntry(entryPath);
                        zipOut.putNextEntry(zipEntry);
                        
                        try (FileInputStream fis = new FileInputStream(fileToZip)) {
                            byte[] buffer = new byte[8192];
                            int length;
                            while ((length = fis.read(buffer)) > 0) {
                                zipOut.write(buffer, 0, length);
                            }
                        }
                        zipOut.closeEntry();
                    }
                }
            }
        }
    }
}
